<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-if="editInfo.editField === 'gender'" name="radio" label="性别">
        <template #input>
          <van-radio-group v-model="editInfo.editValue" direction="horizontal">
            <van-radio name="0">男</van-radio>
            <van-radio name="1">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-else-if="editInfo.editField === 'avatarUrl'" name="avatarUrl" label="头像">
        <template #input>
          <van-image :src="editInfo.editValue" width="50%"/>
        </template>
      </van-field>
      <van-field
          v-else="editInfo.editField !== 'gender'"
          v-model="editInfo.editValue"
          :name="editInfo.editField"
          :label="editInfo.editTitle"
      >
      </van-field>
      <van-checkbox-group style="padding: 10px;" v-if="editInfo.editField === 'userTags'" v-model="checkedTags" direction="horizontal">
        <van-checkbox v-for="childTagName in childrenTags" :name="childTagName">{{ childTagName }}</van-checkbox>
      </van-checkbox-group>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import request from "../../request/request";
import {getChildrenTagList, getCurrentUser} from "../../services/api";
import {showFailToast, showSuccessToast} from "vant";
import {setLoginState} from "../../config/globalState";
const route = useRoute();
const router = useRouter();

const editInfo = ref({
  editField: route.query.editKey,
  editTitle: route.query.title,
  editValue: route.query.currentValue
})

const initCheckedTags = [];
// 选择的标签列表
const checkedTags = ref(initCheckedTags);

// 全部子级别标签列表
const initChildrenTags = [];
const childrenTags = ref(initChildrenTags);

let loginUser = undefined;

onMounted(async () => {
  const currentUser = await getCurrentUser();
  if (currentUser) {
    loginUser = currentUser;
  }
  // 获取全部子级别标签
  const data = await getChildrenTagList();
  if (data && data.length > 0) {
    childrenTags.value = data.map(childTag => {
      return childTag.tagName;
    });
  }

})
const onSubmit = async (values) => {
  const editRes = await request.post('/user/edit', {
    id: loginUser.id,
    [editInfo.value.editField]: editInfo.value.editField === 'userTags' ? JSON.stringify(checkedTags.value) : editInfo.value.editValue
  })
  if (editRes.data.data === true) {
    showSuccessToast('修改成功！');
    // 重新设置缓存状态
    const result = await request.get('/user/current');
    if (result.data.code === 200) {
      setLoginState(result.data.data);
    }
    router.back();
  } else {
    showFailToast('修改失败！');
  }
};
</script>

<style scoped>

</style>